package com.fancy.learncenter.ui.fragment;


import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.czt.mp3recorder.MP3Recorder;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.CartoonStudentSubjectiveDataBean;
import com.fancy.learncenter.bean.CartoonSubmitDataBean;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.common.MAudioPlayer;
import com.fancy.learncenter.common.MyApplication;
import com.fancy.learncenter.common.VideoSentenceDataBean;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.EveryDayWorkActivity;
import com.fancy.learncenter.ui.adapter.CartoonSentenceLvAdapter;
import com.fancy.learncenter.ui.adapter.CartoonSentenceReadAdapter;
import com.fancy.learncenter.ui.view.CustomVedioPlayer;
import com.fancy.learncenter.ui.view.MyTouchListView;
import com.fancy.learncenter.utils.FileUtils;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.TimeUtil;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.listener.VideoAllCallBack;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class CartoonSentenceSpeakReleaseFragment extends BaseFragment {


    public static String RELEASE_FALG = "release";
    public static String playUrl = "http://img1.fancyedu.com/show_manage/audio/story/%5B%E5%A5%97%5D%E8%80%81%E6%95%85%E4%BA%8B-%E5%90%8E%E7%BE%BF%E5%B0%84%E6%97%A5.mp3";
    /**
     * 资源ID
     */
    String resId;
    /**
     * 缓存路径
     */
    String cachDir;
    /**
     * 当前文件地址
     */
    String filePathCurrent = "";
    /**
     * 选中的第几句话（从1开始）
     */
    int onSelect = 1;

    boolean isPlayRecord = false;
    String coverImg = "";

    View rootView;

    String ulrPath = "";
    String speakingPackageId = "";
    boolean isLocal = false;
    boolean isComplete = true;

    String subtitleJsonStr = "";

    List<CartoonStudentSubjectiveDataBean.StemsListBean> stemsListBean;
    @Bind(R.id.complete_tv)
    TextView completeTv;
    @Bind(R.id.total_tv)
    TextView totalTv;

    String recordName;


    String questionsName;
    @Bind(R.id.video_player)
    CustomVedioPlayer videoPlayer;

    private List<String> itemAudids;

    SimpleDraweeView playAudio;

    SimpleDraweeView recordAudio;

    SimpleDraweeView playRecord;

    ProgressBar recordPb;


    public static CartoonSentenceSpeakReleaseFragment newInstance(String cachDir, String subtitleJsonStr, ArrayList<CartoonStudentSubjectiveDataBean.StemsListBean> stemsListBean) {

        Bundle args = new Bundle();


        args.putString("cachDir", cachDir);

        args.putString("subtitleJsonStr", subtitleJsonStr);

        args.putParcelableArrayList("stemsListBean", stemsListBean);

        CartoonSentenceSpeakReleaseFragment fragment = new CartoonSentenceSpeakReleaseFragment();
        fragment.setArguments(args);
        return fragment;
    }

    String type = "";

    public static CartoonSentenceSpeakReleaseFragment newInstance(String cachDir, String subtitleJsonStr, ArrayList<CartoonStudentSubjectiveDataBean.StemsListBean> stemsListBean, String type) {

        Bundle args = new Bundle();


        args.putString("cachDir", cachDir);

        args.putString("subtitleJsonStr", subtitleJsonStr);

        args.putString("type", type);

        args.putParcelableArrayList("stemsListBean", stemsListBean);

        CartoonSentenceSpeakReleaseFragment fragment = new CartoonSentenceSpeakReleaseFragment();

        fragment.setArguments(args);

        return fragment;
    }


    public static CartoonSentenceSpeakFragment newInstance(String speakingPackageId, String resId, String questionsName, String subtitleJsonStr, String cachDir, ArrayList<CartoonStudentSubjectiveDataBean.StemsListBean> stemsListBean) {

        Bundle args = new Bundle();


        args.putString("speakingPackageId", speakingPackageId);
        args.putString("resId", resId);

        args.putString("questionsName", questionsName);
        args.putString("subtitleJsonStr", subtitleJsonStr);

        args.putString("cachDir", cachDir);

        args.putParcelableArrayList("stemsListBean", stemsListBean);

        CartoonSentenceSpeakFragment fragment = new CartoonSentenceSpeakFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            this.resId = getArguments().getString("resId");
            this.cachDir = getArguments().getString("cachDir");
            this.stemsListBean = getArguments().getParcelableArrayList("stemsListBean");

            this.subtitleJsonStr = getArguments().getString("subtitleJsonStr");
            this.speakingPackageId = getArguments().getString("speakingPackageId");
            this.questionsName = getArguments().getString("questionsName");
            this.type = getArguments().getString("type");

            for (int i = 0; i < stemsListBean.size(); i++) {
                switch (stemsListBean.get(i).getKey()) {
                    case "text":
                        break;
                    case "video_url":
                        ulrPath = stemsListBean.get(i).getValue();
                        break;
                    case "audio_url":
                        playUrl = stemsListBean.get(i).getValue();
                        break;
                    case "cover_img_url":
                        coverImg = stemsListBean.get(i).getValue();
                        break;
                }
            }
        }
    }

    LinearLayoutManager manager;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_cartoon_sentence_speak, container, false);
        ButterKnife.bind(this, rootView);
        init(ulrPath);

        initSentence();

        initRecycle();

        return rootView;
    }

    List<VideoSentenceDataBean> captionDatas = new ArrayList();

    CartoonSentenceReadAdapter cartoonSentenceReadAdapter;

    private void initRecycle() {

        for (int i = 0; i < captionDatas.size(); i++) {
            captionDatas.get(i).setStatus(1);
        }
        if (!TextUtils.isEmpty(type)) {
            cartoonSentenceLvAdapter = new CartoonSentenceLvAdapter(getActivity(), captionDatas, type);
        } else {
            cartoonSentenceLvAdapter = new CartoonSentenceLvAdapter(getActivity(), captionDatas, "1");

            cartoonSentenceReadAdapter = new CartoonSentenceReadAdapter(getActivity(), captionDatas);
        }


//        recyclerView.setmOnListViewChange(new MyTouchListView.OnListViewChange() {
//            @Override
//            public void onTouchDown() {
//
//            }
//
//            @Override
//            public void onTouchMove(int firstVisiblePosition) {
//
//            }
//
//            @Override
//            public void onTOuchUp(int firstVisiblePosition) {
//
//            }
//
//            @Override
//            public void onAnimFinish(int firstVisiblePosition) {
//
//                if (firstVisiblePosition == captionDatas.size()) {
//                    return;
//                }
//
//                curPotion = firstVisiblePosition;
//
//
//                onSelect = firstVisiblePosition + 1;
//                filePathCurrent = cachDir + onSelect + ".mp3";
//                File fileCurrent = new File(filePathCurrent);
//                if (fileCurrent.exists()) {
//
//                    captionDatas.get(curPotion).setStatus(1);
//
//                } else {
//
//                    captionDatas.get(curPotion).setStatus(0);
//
//                }
//
//                cartoonSentenceLvAdapter.setSelectItem(curPotion, false);
//
//
//                View view = recyclerView.getChildAt(firstVisiblePosition - recyclerView.getFirstVisiblePosition());
//                CartoonSentenceLvAdapter.ViewHolder holder = (CartoonSentenceLvAdapter.ViewHolder) view.getTag();
//                playAudio = holder.video_voice_icon;
////
//                recordAudio = holder.record_icon;
////
//                playRecord = holder.play_record_icon;
//
//                recordPb = holder.record_pb;
//
//
//            }
//        });

        cartoonSentenceLvAdapter.setOnClickCallBack(new CartoonSentenceLvAdapter.OnClickCallBack() {
            @Override
            public void recordClick() {
                if (isComplete) {
                    isComplete = false;
                    pausePlayRecord();
                    playVideo(true);
                    changeRecordUi();
                }
            }

            @Override
            public void videoClick() {
                if (isComplete) {
                    isComplete = false;
                    pauseRecorder();

                    pausePlayRecord();

                    if (GSYVideoManager.instance().getMediaPlayer().isPlaying()) {
                        videoPlayer.onVideoPause();
                    } else {
                        playVideo(false);
                    }
                }
            }

            @Override
            public void playRecordClick() {
                if (isComplete) {
                    isComplete = false;
                    if (TextUtils.isEmpty(filePathCurrent) || !new File(filePathCurrent).exists()) {
                        ToastUtil.show("小朋友，请先录制单词吧");
                        isComplete = true;
                    } else {
                        pauseRecorder();
                        playOrPauseRecord();
                    }
                }

            }
        });


        int listview_footView_height = Utils.getScreeHeight() - Utils.getStatusBarHeight() - Utils.dip2pix(getActivity(), 200);
        //实例化数据库
        View footView = LayoutInflater.from(getActivity()).inflate(R.layout.cartoon_sentence_footer_view, null);
        final AbsListView.LayoutParams params = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, listview_footView_height);
        footView.setLayoutParams(params);
//        recyclerView.addFooterView(footView);
//
//
//        recyclerView.setAdapter(cartoonSentenceLvAdapter);

        handler.postDelayed(runnable, 500);
    }


    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
//            View view = recyclerView.getChildAt(0);

//            CartoonSentenceLvAdapter.ViewHolder holder = (CartoonSentenceLvAdapter.ViewHolder) view.getTag();
//
//            playAudio = holder.video_voice_icon;
//
//            recordAudio = holder.record_icon;
//
//            playRecord = holder.play_record_icon;
//
//            recordPb = holder.record_pb;
        }
    };

    CartoonSentenceLvAdapter cartoonSentenceLvAdapter;

    @Override
    public void onResume() {
        super.onResume();
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (!isVisibleToUser) {
            resetMedio();
        } else {

            if (completeTv != null) {

                if (getActivity() instanceof EveryDayWorkActivity) {
                    completeTv.setText(((EveryDayWorkActivity) getActivity()).completeNum + "");
                }

            }

        }

        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        try {
            stopMedio();
        } catch (Exception e) {

        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    @OnClick({R.id.play_audio, R.id.record_audio, R.id.play_record})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.play_audio:

                if (isComplete) {
                    pauseRecorder();
                    pausePlayRecord();

                    if (GSYVideoManager.instance().getMediaPlayer().isPlaying()) {
                        videoPlayer.onVideoPause();
                    } else {
                        playVideo(false);
//                    videoPlayer.st();
                    }
                }
                isComplete = false;

                break;
            case R.id.record_audio:


                if (isComplete) {
                    pausePlayRecord();
                    playVideo(true);
                    changeRecordUi();
                }
                isComplete = false;
                break;
            case R.id.play_record:

                if (isComplete) {
                    pauseRecorder();
                    playOrPauseRecord();
                }
                isComplete = false;
                break;
        }
    }

    @Override
    public void onPause() {
        super.onPause();

        resetMedio();
    }

    boolean isMute = false;

    private void init(String urlPath) {

//        videoPlayer.setPositionCallBack(new CustomVedioPlayer.PositionCallBack() {
//            @Override
//            public void positon(int positon) {
//            }
//
//            @Override
//            public void onCompletion() {
//                TimeUtil.cancle();
//            }
//
//            @Override
//            public void onPause() {
//                TimeUtil.cancle();
//            }
//        });

        //需要路径的
        videoPlayer.setUp(urlPath, true, new File(FileUtils.getCartoonPath()), "环球少年");
//        //增加封面
        SimpleDraweeView imageView = new SimpleDraweeView(getActivity());
        imageView.setImageURI(coverImg);
        videoPlayer.setThumbImageView(imageView);

        //增加title
        videoPlayer.getTitleTextView().setVisibility(View.GONE);

        videoPlayer.setBottomProgressBarDrawable(getResources().getDrawable(R.drawable.video_new_progress));

        videoPlayer.setDialogVolumeProgressBar(getResources().getDrawable(R.drawable.video_new_volume_progress_bg));

        videoPlayer.setDialogProgressBar(getResources().getDrawable(R.drawable.video_new_progress));

        videoPlayer.setBottomShowProgressBarDrawable(getResources().getDrawable(R.drawable.video_new_seekbar_progress),
                getResources().getDrawable(R.drawable.video_new_seekbar_thumb));

        videoPlayer.setDialogProgressColor(getResources().getColor(R.color.yellow), getResources().getColor(R.color.white));

        videoPlayer.getFullscreenButton().setVisibility(View.GONE);
        videoPlayer.setDismissControlTime(500);
        videoPlayer.onPrepared();

        videoPlayer.setPositionCallBack(new CustomVedioPlayer.PositionCallBack() {
            @Override
            public void positon(int positon) {
                LogUtil.MyLog("setPositionCallBack", "=====positon===");
            }

            @Override
            public void onCompletion() {
                LogUtil.MyLog("setPositionCallBack", "=====onCompletion===");
            }

            @Override
            public void onPause() {
                LogUtil.MyLog("setPositionCallBack", "=====onPause===");
            }
        });
//        videoPlayer.setGSYVideoProgressListener();
        videoPlayer.setVideoAllCallBack(new VideoAllCallBack() {
            @Override
            public void onPrepared(String url, Object... objects) {
                LogUtil.MyLog("setVideoAllCallBack", "=====onPrepared===");
                GSYVideoManager.instance().setNeedMute(isMute);
                startTimer(deleteTime);
            }

            @Override
            public void onClickStartIcon(String url, Object... objects) {
                LogUtil.MyLog("setVideoAllCallBack", "=====onClickStartIcon===");
            }

            @Override
            public void onClickStartError(String url, Object... objects) {
                LogUtil.MyLog("setVideoAllCallBack", "=====onClickStartError===");
            }

            @Override
            public void onClickStop(String url, Object... objects) {
                LogUtil.MyLog("setVideoAllCallBack", "=====onClickStop===");
            }

            @Override
            public void onClickStopFullscreen(String url, Object... objects) {
                LogUtil.MyLog("setVideoAllCallBack", "=====onClickStopFullscreen===");
            }

            @Override
            public void onClickResume(String url, Object... objects) {
                LogUtil.MyLog("setVideoAllCallBack", "=====onClickResume===");
            }

            @Override
            public void onClickResumeFullscreen(String url, Object... objects) {
                LogUtil.MyLog("setVideoAllCallBack", "=====onClickResumeFullscreen===");
            }

            @Override
            public void onClickSeekbar(String url, Object... objects) {
                LogUtil.MyLog("setVideoAllCallBack", "=====onClickSeekbar===");
            }

            @Override
            public void onClickSeekbarFullscreen(String url, Object... objects) {
                LogUtil.MyLog("setVideoAllCallBack", "=====onClickSeekbarFullscreen===");
            }

            @Override
            public void onAutoComplete(String url, Object... objects) {
                LogUtil.MyLog("setVideoAllCallBack", "=====onAutoComplete===");
            }

            @Override
            public void onEnterFullscreen(String url, Object... objects) {
                LogUtil.MyLog("setVideoAllCallBack", "=====onEnterFullscreen===");
            }

            @Override
            public void onQuitFullscreen(String url, Object... objects) {
                LogUtil.MyLog("setVideoAllCallBack", "=====onQuitFullscreen===");
            }

            @Override
            public void onQuitSmallWidget(String url, Object... objects) {
                LogUtil.MyLog("setVideoAllCallBack", "=====onQuitSmallWidget===");
            }

            @Override
            public void onEnterSmallWidget(String url, Object... objects) {
                LogUtil.MyLog("setVideoAllCallBack", "=====onEnterSmallWidget===");
            }

            @Override
            public void onTouchScreenSeekVolume(String url, Object... objects) {
                LogUtil.MyLog("setVideoAllCallBack", "=====onTouchScreenSeekVolume===");
            }

            @Override
            public void onTouchScreenSeekPosition(String url, Object... objects) {
                LogUtil.MyLog("setVideoAllCallBack", "=====onTouchScreenSeekPosition===");
            }

            @Override
            public void onTouchScreenSeekLight(String url, Object... objects) {
                LogUtil.MyLog("setVideoAllCallBack", "=====onTouchScreenSeekLight===");
            }

            @Override
            public void onPlayError(String url, Object... objects) {
                LogUtil.MyLog("setVideoAllCallBack", "=====onPlayError===");
            }

            @Override
            public void onClickStartThumb(String url, Object... objects) {
                LogUtil.MyLog("setVideoAllCallBack", "=====onClickStartThumb===");
            }

            @Override
            public void onClickBlank(String url, Object... objects) {
                LogUtil.MyLog("setVideoAllCallBack", "=====onClickBlank===");
            }

            @Override
            public void onClickBlankFullscreen(String url, Object... objects) {
                LogUtil.MyLog("setVideoAllCallBack", "=====onClickBlankFullscreen===");
            }
        });
    }

    int curPotion = 0;

    private void startTimer(int secoend) {

        if (isMute) {
            recordPb.setVisibility(View.VISIBLE);
        } else {
            recordPb.setVisibility(View.INVISIBLE);


            String urlPath = "res://com.fancy.learncenter/" + R.mipmap.cartoon_voice_g_icon;
            DraweeController draweeController =
                    Fresco.newDraweeControllerBuilder()
                            .setUri(urlPath)
                            .setOldController(playAudio.getController())
                            .setAutoPlayAnimations(true) // 设置加载图片完成后是否直接进行播放
                            .build();
            playAudio.setController(draweeController);
        }

        LogUtil.MyLog("videoPlayersvideoPlayers", "=======start========" + startTime);
        LogUtil.MyLog("videoPlayersvideoPlayers", "=======endTime========" + endTime);
        LogUtil.MyLog("videoPlayersvideoPlayers", "=======secoend========" + secoend);

//        recyclerView.setMove(true);
        TimeUtil.interval((secoend + 500) / 100, new TimeUtil.TimeCallBack() {
            /**
             * 计时中
             *
             * @param time
             */
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void nextCallBack(long time) {
                LogUtil.MyLog("videoPlayers", "=======completeCallBack========");
                if (time > 100) {
//                    recyclerView.setMove(false);
                    isComplete = true;
                    LogUtil.MyLog("videoPlayersvideoPlayers", time + "=======endvoice========" + time * 100);
                    videoPlayer.onVideoPause();
                    TimeUtil.cancle();
                    if (isMute) {
                        pauseRecorder();
                    }
                    cartoonSentenceLvAdapter.setSelectItem(curPotion, false);
//                    cartoonSentenceLvAdapter.notifyDataSetChanged();
                } else {
                    recordPb.setProgress((int) time);
                }
            }

            /**
             * 计时完成
             */
            @Override
            public void completeCallBack() {

                cartoonSentenceLvAdapter.setSelectItem(curPotion, false);
                LogUtil.MyLog("videoPlayers", "=======completeCallBack========");

//                recordAudio.setImageURI(Uri.parse("res://com.fancy.learncenter/" + R.mipmap.cartoon_record_icon));
//
//                playAudio.setImageURI(Uri.parse("res://com.fancy.learncenter/" + R.mipmap.cartoon_voice_icon));
            }

            /**
             * 计时开始
             */
            @Override
            public void startCallBack() {
                LogUtil.MyLog("videoPlayers", "=======startCallBack========");
            }
        });
    }

    int deleteTime = 0;
    int startTime;
    int endTime;
    int totalTime;


    /**
     * 播放   视频某一段落
     */
    private void playVideo(boolean isMute) {
        recordPb.setMax(100);
        recordPb.setProgress(0);
        this.isMute = isMute;
        startTime = captionDatas.get(onSelect - 1).getCurStart();
        endTime = captionDatas.get(onSelect - 1).getCurEnd();
        deleteTime = endTime - startTime;

        videoPlayer.setSeekOnStart(startTime);

//        videoPlayer.setPlayPosition(startTime);
        videoPlayer.startPlayLogic();
//        videoPlayer.setSeekOnStart();
    }

    /**
     * 暂停   视频
     */
    private void pauseVideo() {

        if (videoPlayer != null) {
            videoPlayer.onVideoPause();
            TimeUtil.cancle();
        }

    }

    /**
     * 停止   播放视频
     */
    private void stopVideo() {
        if (videoPlayer != null) {
            videoPlayer.removeAllViews();
            videoPlayer.release();
        }
        TimeUtil.cancle();
    }

    /**
     * 录音
     */
    MP3Recorder mRecorder;
    /**
     * 录音  播放
     */
    MAudioPlayer recordPlayer;

    /**
     * 开始 录音
     */
    private void resolveRecord() {
        File file = new File(cachDir);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                Toast.makeText(getActivity(), "创建文件失败", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        saveLoacal();
        filePathCurrent = cachDir + onSelect + ".mp3";
        FileUtils.deleteFile(filePathCurrent);

        mRecorder = new MP3Recorder(new File(filePathCurrent));

        mRecorder.setErrorHandler(new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == MP3Recorder.ERROR_TYPE) {
                    resolveError();
                }
            }
        });

        startRecorderUi();
    }

    /**
     * 录音状态改变
     */
    private void changeRecordUi() {
        if (mRecorder != null) {
            if (mRecorder.isRecording()) {
                LogUtil.MyLog("mRcorder", "=======暂停录音=====");
                pauseRecorder();
            } else {
                LogUtil.MyLog("mRecorder", "=======继续录音=====");
                resolveRecord();
            }

        } else {
            resolveRecord();
        }

//
    }

    /**
     * 录音异常
     */
    private void resolveError() {
        FileUtils.deleteFile(filePathCurrent);
        if (mRecorder != null && mRecorder.isRecording()) {
            mRecorder.stop();
        }
    }

    /**
     * 开始录音ui
     */
    private void startRecorderUi() {
        try {


            if (getActivity() instanceof EveryDayWorkActivity) {
                ((EveryDayWorkActivity) getActivity()).changeUi(true);
            }


            mRecorder.start();

//            recyclerView.setMove(true);


//            String urlPath = "res://com.fancy.learncenter/" + R.mipmap.cartoon_record_g_icon;
//            DraweeController draweeController =
//                    Fresco.newDraweeControllerBuilder()
//                            .setUri(urlPath)
//                            .setOldController(playAudio.getController())
//                            .setAutoPlayAnimations(true) // 设置加载图片完成后是否直接进行播放
//                            .build();
//            recordAudio.setController(draweeController);
//            recordAudio.setClickable(false);

            playRecord.setImageURI(Uri.parse("res://com.fancy.learncenter/" + R.mipmap.cartoon_pause_cion));
            recordAudio.setImageURI(Uri.parse("res://com.fancy.learncenter/" + R.mipmap.cartoon_record_g_icon));

        } catch (IOException e) {
            e.printStackTrace();
            LogUtil.MyLog("mRecorder", "======mRecorder=====" + e);
            Toast.makeText(getActivity(), "录音出现异常，请重试", Toast.LENGTH_SHORT).show();
            resolveError();
            pauseRecorder();
            return;
        }
    }

    /**
     * 停止录音ui
     */
    private void pauseRecorder() {
//        if (recyclerView != null) {
//            recyclerView.setMove(false);
//        }

        if (mRecorder != null) {
            mRecorder.stop();
        }

        if (recordAudio != null) {
            recordAudio.setImageURI(Uri.parse("res://com.fancy.learncenter/" + R.mipmap.cartoon_record_icon));
            playRecord.setImageURI(Uri.parse("res://com.fancy.learncenter/" + R.mipmap.cartoon_pause_cion));

            captionDatas.get(curPotion).setStatus(1);
            cartoonSentenceLvAdapter.notifyDataSetChanged();
            recordAudio.setClickable(true);
        }

    }


    /**
     * 暂停播放录音资源
     */
    private void pausePlayRecord() {
        if (recordPlayer != null) {
            recordPlayer.pause();
        }
    }


    /**
     * 暂停播放录音资源
     */
    private void stopPlayRecord() {
        if (recordPlayer != null) {
            recordPlayer.stop();
        }
    }

    /**
     * 播放或者暂停 录音音频
     */
    private void playOrPauseRecord() {
        if (TextUtils.isEmpty(filePathCurrent) || !new File(filePathCurrent).exists()) {
            ToastUtil.show("小朋友，请先录制单词吧");
            return;
        }
        playVideo(true);
        if (recordPlayer != null) {
            if (recordPlayer.isPlaying()) {
                recordPlayer.pause();
            } else {
                recordPlayer.playUrl(filePathCurrent);
            }
        } else {
            recordPlayer = new MAudioPlayer();
            recordPlayer.setAudioPlayerStatus(new MAudioPlayer.AudioPlayerStatus() {
                @Override
                public void playerPause() {
                    if (playRecord != null) {
                        playRecord.setImageURI(Uri.parse("res://com.fancy.learncenter/" + R.mipmap.cartoon_pause_cion));
                    }
                    pauseVideo();
                }

                @Override
                public void playerCompletion(MediaPlayer mp) {
                    recordPb.setVisibility(View.INVISIBLE);
                    playRecord.setImageURI(Uri.parse("res://com.fancy.learncenter/" + R.mipmap.cartoon_pause_cion));
                    pauseVideo();

                }

                @Override
                public void playerPrepared(MediaPlayer mp) {
                    recordPlayer.play();
                }

                @Override
                public void playerStart() {
                    playRecord.setImageURI(Uri.parse("res://com.fancy.learncenter/" + R.mipmap.cartoon_play_icon));
                    playVideo(true);
                }

                @Override
                public void playerError(MediaPlayer mp, int what, int extra) {
                    recordPb.setVisibility(View.INVISIBLE);
                    playRecord.setImageURI(Uri.parse("res://com.fancy.learncenter/" + R.mipmap.cartoon_pause_cion));
                }
            });
            recordPlayer.playUrl(filePathCurrent);
        }

    }


    private void resetMedio() {
        TimeUtil.cancle();

        pauseRecorder();

        pauseVideo();

        pausePlayRecord();


    }


    private void stopMedio() {

        TimeUtil.cancle();

        pauseRecorder();

        stopVideo();

        stopPlayRecord();

    }

    private void initSentence() {
        String result = "[ {\"index\":0,\"curStart\":1,\"curEnd\":4500,\"transcript\":\"\\u9996\\u5148\\uff0c\\u6211\\u4f1a\\u6559\\u4f60\\u4eec\\u5982\\u4f55\\u628a\\u7403\\u4ece\\u8fd9\\u91cc\\u2026\\u2026\",\"translations\":\"First, I'll teach you how to get the ball from here……\"},  {\"index\":1,\"curStart\":4500,\"curEnd\":6200,\"transcript\":\"\\u8fd0\\u5230\\u8fd9\\u91cc\",\"translations\":\"to here.\"},  {\"index\":2,\"curStart\":6200,\"curEnd\":9600,\"transcript\":\"\\u6211\\u80fd\\u505a\\u5230\\u3002\",\"translations\":\"I can do that.\"},  {\"index\":3,\"curStart\":9600,\"curEnd\":10700,\"transcript\":\"\\u4e0d\\uff0c\\u4e39\\u5c3c\\u3002\",\"translations\":\"No, Danny.\"},  {\"index\":4,\"curStart\":10700,\"curEnd\":13800,\"transcript\":\"\\u4f60\\u4e0d\\u80fd\\u7528\\u811a\\uff0c\\u90a3\\u662f\\u8db3\\u7403\\u3002\",\"translations\":\"You can't use your feet. That's football.\"},  {\"index\":5,\"curStart\":13800,\"curEnd\":16000,\"transcript\":\"\\u5c0f\\u72d7\\u4e39\\u5c3c\\u559c\\u6b22\\u8db3\\u7403\\u3002\",\"translations\":\"Danny dog likes football.\"},  {\"index\":6,\"curStart\":16000,\"curEnd\":17440,\"transcript\":\"\\u5728\\u7bee\\u7403\\u89c4\\u5219\\u4e2d\\uff0c\",\"translations\":\"In basketball,\"},  {\"index\":7,\"curStart\":17440,\"curEnd\":21930,\"transcript\":\"\\u4f60\\u9700\\u8981\\u7528\\u624b\\u62cd\\u7403\\uff0c\\u5c31\\u50cf\\u8fd9\\u6837\\u3002\",\"translations\":\"you bounce the ball with your hands, like this\"}]";
        Gson g = new Gson();
        ArrayList<VideoSentenceDataBean> curList = null;
        try {
            curList = g.fromJson(result, new TypeToken<List<VideoSentenceDataBean>>() {
            }.getType());
        } catch (Exception e) {
            e.printStackTrace();
        }
        captionDatas = curList;

    }


    @Override
    public String fmCallBackValue() {
        return null;
    }

    @Override
    public String fmCallBackName() {
        return null;
    }

    @Override
    public void fmCallBack() {
        ArrayList<String> fileDatas = new ArrayList<>();
        if (FileUtils.getDirNum(cachDir) >= captionDatas.size()) {

            for (int i = 0; i < captionDatas.size(); i++) {
                String filePath = cachDir + (i + 1) + ".mp3";
                File file = new File(filePath);
                if (file.exists()) {
                    fileDatas.add(filePath);
                }
            }
            try {
//                FileUtils.deleteFile(cachDir + "record.mp3");
//                boolean isCombine = FileUtils.combine(cachDir + "record.mp3", fileDatas);
                submitData(fileDatas);
//                if (isCombine) {
//                    submitData(fileDatas);
//                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            ToastUtil.show("小朋友录完句子，再提交吧");
            return;
        }
    }

    boolean isSubmit = false;

    private void submitData(ArrayList<String> filePaths) {

        if (isSubmit) {
            return;
        }
        Map maps = new HashMap<>();
//
//        if (TextUtils.isEmpty(filePath)) {
//            return;
//        }
//        File mp3File = new File(filePath);
//
//        if (!mp3File.exists()) {
//            return;
//        }

        for (int i = 0; i < captionDatas.size(); i++) {
            File mp3File = new File(filePaths.get(i));
            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), mp3File);
            maps.put("file\"; filename=\"" + i + ".mp3", requestFile);
        }


        maps.put("classId", RequestBody.create(MediaType.parse("text/plain"), MyApplication.classIDStr));

        maps.put("speakingPackageId", RequestBody.create(MediaType.parse("text/plain"), speakingPackageId));

        maps.put("subjectQuestionId", RequestBody.create(MediaType.parse("text/plain"), resId));

        maps.put("type", RequestBody.create(MediaType.parse("text/plain"), "1" + ""));

        HttpMehtod.getInstance().submitWork(maps, new CustomNetSubscriber(getActivity()) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                BaseBean<CartoonSubmitDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonSubmitDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonSubmitDataBean>() {
                    @Override
                    public void success(CartoonSubmitDataBean dataBean) {
                        ToastUtil.show("上传成功");

                        ((EveryDayWorkActivity) getActivity()).addCompeleteNum();
                        completeTv.setText(((EveryDayWorkActivity) getActivity()).getCompeleteNum() + "");
                        isSubmit = true;

                        renameDirectory(cachDir, releaseDir);

                        if (getActivity() instanceof EveryDayWorkActivity) {
                            completeTv.setText(((EveryDayWorkActivity) getActivity()).completeNum + "");
                        }

                    }

                    @Override
                    public void fail(String errorCode) {
                        ToastUtil.show("上传失败");
                    }
                }).dealData();
            }
        });
    }

    String releaseDir;

    public void renameDirectory(String fromDir, String toDir) {

        File from = new File(fromDir);

        if (!from.exists() || !from.isDirectory()) {
            System.out.println("Directory does not exist: " + fromDir);
            return;
        }

        File to = new File(toDir);

        //Rename
        if (from.renameTo(to)) {
            Utils.saveLocalRecorder(recordName + Constant.DIVID_CODE + RELEASE_FALG, resId, coverImg, questionsName, videoPlayer.getDuration(), System.currentTimeMillis());
        } else {
            System.out.println("Error");
        }


    }

    boolean isRecord = true;

    private void saveLoacal() {
        if (isRecord) {
            isRecord = false;
            Utils.saveLocalRecorder(recordName, resId, coverImg, questionsName, videoPlayer.getDuration(), System.currentTimeMillis());
        }

    }
}
